package org.study.shardingsphere.boot.config;

import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.driver.api.yaml.YamlShardingSphereDataSourceFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.*;
import org.springframework.util.ResourceUtils;

import javax.sql.DataSource;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lenovo
 */
@Slf4j
@Configuration
public class DataSourceConfig {
    @Bean("writeDataSource")
    @ConfigurationProperties("spring.datasource.write-ds")
    public DataSource writeDataSource() {
        return new HikariDataSource();
    }

    @Bean("readDataSource1")
    @ConfigurationProperties("spring.datasource.read-ds1")
    public DataSource readDataSource1() {
        return new HikariDataSource();
    }

    @Bean("readDataSource2")
    @ConfigurationProperties("spring.datasource.read-ds2")
    public DataSource readDataSource2() {
        return new HikariDataSource();
    }

    @Primary
    @Bean("dataSource")
    public DataSource dataSource(@Qualifier("writeDataSource") DataSource writeDataSource,
                                 @Qualifier("readDataSource1") DataSource readDataSource1,
                                 @Qualifier("readDataSource2") DataSource readDataSource2) throws Exception {
        Map<String, DataSource> dataSourceMap = new HashMap<>() {{
            put("write_ds", writeDataSource);
            put("read_ds1", readDataSource1);
            put("read_ds2", readDataSource2);
        }};
        File ruleFile = ResourceUtils.getFile("classpath:sharding.yaml");
        return YamlShardingSphereDataSourceFactory.createDataSource(dataSourceMap, ruleFile);
    }
}